package org.ydsw.data.manage.schedule;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
import org.ydsw.data.manage.utils.RRException;
import org.ydsw.data.manage.utils.SpringContextUtils;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 执行定时任务
 * @author admin
 * @date 2021年01月05日
 */
@Slf4j
public class ScheduleRunnable implements Runnable {
    private Object target;
    private Method method;
    private String params;

    /**
     * 设定定时任务情况
     * @param beanName
     * @param methodName
     * @param params
     * @throws NoSuchMethodException
     * @throws SecurityException
     */
    public ScheduleRunnable(String beanName, String methodName, String params) throws NoSuchMethodException, SecurityException {
        this.target = SpringContextUtils.getBean(beanName);
        this.params = params;
        //根据参数情况，执行不同的定时任务
        if (StringUtils.isNotBlank(params)) {
            this.method = target.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    /**
     * 运行定时任务计划
     */
    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isNotBlank(params)) {
                //按参数激活定时任务
                method.invoke(target, params);
            } else {
                //执行定时任务
                method.invoke(target);
            }
        } catch (IllegalAccessException|IllegalArgumentException|
                InvocationTargetException e) {
            e.printStackTrace();
            throw new RRException("执行定时任务失败", e);
        }
    }

}
